<?php
			
	/* SVN FILE: $Id: api.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/include/api.php $
	 */

	date_default_timezone_set('Europe/Rome');

	if(isset($_GET['sAPP']) && !empty($_GET['sAPP'])) {
		$sAPP = $_GET['sAPP'];	
	
	} else {
		require_once "./const.inc.php";
		require_once "./functions.php";
		require_once "./auth.inc.php";
		require_once "./conn.inc.php";
		
		fnUpdateLog('APP NOT DEFINED', 0, '', 'E');
		echo fnJsonOutput(fnCurrentScript(), '', '', 888);
		die();
	
	}

	require_once "../$sAPP/include/const.inc.php";
	require_once "../$sAPP/include/functions.php";
	// require_once 'include/auth.inc.php';
	require_once "conn.inc.php";
	
	if (!isset($_SESSION)) { session_start(); }
	
	fnGetValueFromGET(array('sAction','sSearchTerms'));
	
	if(!isset($sTable) || !isset($aTABLE[$sTable])) {
		$sTable = fnTableDefault($sTABLE_DEFAULT, $aTABLE);
	}
	
	fnTableConst($sTable);
	
	$sOutput = '';
				
	switch ($sAction) {
	
		case 'opensearch' :
		
			if (isset($bSEARCH_FORM_SHOW) && $bSEARCH_FORM_SHOW) { 
		
				if (!isset($sWhere) || trim($sWhere)=='') { $sWhere = " 1 "; }
		
				// $sWhere
				if (trim($sTableSelectWhere) != '1') {
					$sWhere .= " AND ".$sTableSelectWhere; 	
				}

				if (!is_null(fnReadSessionValue('sUsername'))) {
					$sWhere .= fnSearchFilter('sWhere', $sSearchTerms, $aSearchFields);

				} else {
					// se l'utente non ha eseguito il login viene permessa la ricerca solo nel campo
					// definito nella variabile $sSEARCH_JSON_OUTPUT
					$sWhere .= fnSearchFilter('sWhere', $sSearchTerms, array($sSEARCH_JSON_OUTPUT));	
				
				}
				
				$sQuery = "
					SELECT SQL_CALC_FOUND_ROWS 
					$sSEARCH_JSON_OUTPUT
					FROM $sTableSelectFrom
					WHERE $sWhere
					GROUP BY ".($sTableSelectGroupBy != '' ? " $sTableSelectGroupBy, " : "")." $sSEARCH_JSON_OUTPUT ";

				$rResult = custom_mysql_query($sQuery);
		
				$sOutput .= "[\"$sSearchTerms\",";
					$sOutput .= "[";		
					if (mysql_num_rows($rResult) > 0) {	
						while ($aRow = mysql_fetch_array($rResult)) {
							$sOutput .= "\"".preg_replace("/\"/", "\\\"", $aRow[$sSEARCH_JSON_OUTPUT])."\", ";
						}
						$sOutput = substr_replace($sOutput, '', -2);
					}
					$sOutput .= "]";
				$sOutput .= "]";
		
			}	
		break;
	}
	
	echo $sOutput;
	
?>